package com.yubest.security.service.impl;

import com.yubest.security.bean.UserInfo;
import com.yubest.security.consts.Consts;
import com.yubest.security.service.TokenService;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class TokenServiceImpl implements TokenService {

    private Map<String, UserInfo> tokenMap = new HashMap<>();

    @Override
    public String create(UserInfo userInfo) {
        String token = UUID.randomUUID().toString();
        userInfo.setToken(token);
        tokenMap.put(token, userInfo);
        return token;
    }

    @Override
    public boolean verify(String token) {
        if (null == token) {
            return false;
        }
        UserInfo userInfo = get(token);
        return null != userInfo;
    }

    @Override
    public UserInfo get(String token) {
        if (null == token) {
            return null;
        }
        return tokenMap.get(token);
    }

    @Override
    public void remove(String token) {
        if (null != token) {
            tokenMap.remove(token);
        }
    }

    @Override
    public UserInfo getCurrentUser() {
        String token = getCurrentToken();
        return get(token);
    }

    @Override
    public String getCurrentToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(Consts.TOKEN_KEY);
        if (null == token) {
            token = request.getParameter(Consts.TOKEN_KEY);
        }
        return token;
    }
}
